package cn.bossfriday.im.common.rpc.message;

import cn.bossfriday.common.router.RoutableBean;
import cn.bossfriday.common.router.RoutableBeanFactory;
import cn.bossfriday.common.utils.GsonUtil;
import cn.bossfriday.common.utils.UUIDUtil;
import cn.bossfriday.im.common.rpc.IRpcMessage;
import cn.bossfriday.im.common.rpc.RpcMessageContext;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang.StringUtils;

/**
 * ApiMessage
 *
 * @author chenx
 */
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ApiMessage implements IRpcMessage {

    private long appId;

    private String apiVersion;

    private String method;

    private String requesterId;

    private String targetId;

    private Object payload;

    private String logId;

    @Override
    public RoutableBean<Object> getRoutableBean() {
        String routableResourceId = RpcMessageContext.getRouteResourceId(this.appId, this.targetId);
        return RoutableBeanFactory.buildResourceIdRouteBean(this.appId, this.method, routableResourceId, this);
    }

    @Override
    public RpcMessageContext buildContext() {
        return RpcMessageContext.builder()
                .appId(this.appId)
                .apiVersion(this.apiVersion)
                .method(this.method)
                .requesterId(this.requesterId)
                .targetId(this.targetId)
                .sendTime(System.currentTimeMillis())
                .logId(StringUtils.isEmpty(this.logId) ? UUIDUtil.getShortString() : this.logId)
                .messageClass(ApiMessage.class.getName())
                .build();
    }

    @Override
    public String toString() {
        return GsonUtil.toJson(this);
    }
}
